<?php 

class App_Controller_Action_Crud extends App_Controller_Action_Backend {
	
	protected $_model = null;
	
	function init() {
		parent::init();
	}
	
	/**
	 * 
	 * index, wyświetlenie rekordów na podstawie selecta z modelu
	 */
	public function indexAction() {
		
		$sort 		= $this->_getParam('sort', 'id');
		$sortdir 	= $this->_getParam('sortdir', 'desc');
		
		$select = $this->_model->fetchItemsSelect($sort, $sortdir);
		
		$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
		
		$paginator = new Zend_Paginator($adapter);
		$paginator
			->setCurrentPageNumber($this->_getParam('page', 1))
			->setItemCountPerPage($this->_getParam('perpage', 10))
			;
		
		$this->view->paginator = $paginator;
	}
	
	/**
	 * 
	 * edycja
	 */
	public function editAction() {
		
		$id   = (int) $this->_getParam('id');
		
		$form = $this->editForm((bool)$id);
		
		
		if ($this->_request->isPost()) {
			if ($form->isValid($_POST)) {
				if ($id) {
					try {
						$this->_model->update($form->getValues(), $id);
						$this->addMessage('Rekord został zapisany');
					} catch (Exception $e) {
						$this->addMessage('Rekord nie został zapisany', 'error');
					}
				} else {
					try {
						$this->_model->insert($form->getValues());
						$this->addMessage('Rekord został dodany');
					} catch (Exception $e) {
						$this->addMessage('Rekord nie został dodany', 'error');
					}
				}
				$this->_redirect($this->view->url(array('action'=>'index', 'id'=>null)));
			} 
		} else {
			if ($id) {
				$item = $this->_model->fetchItemForEdit($id);
				$form->populate($item);
			}
		}
		
		
		
		$this
			->view
				->assign('form', $form)
				->assign('editMode', (bool)$id );
	}
	
	/**
	 * 
	 * utworzenie nowego rekordu
	 */
	public function createAction() {
		$this->_forward('edit');
	}
	
	/**
	 * 
	 * zmiana dowolnej kolumny tinyint(1) lub bool
	 * parametry 
	 * 	$id - id rekordu lub tablica zawierająca id rekordów
	 * 	$key - kolumna w rekordzie
	 * 	$flag - nowa flaga, jeśli nie jest podana to podana to flaga zostanie zmieniona na przeciwstawną do obecnej
	 */
	public function flagAction() {
		$ids = (array)$this->_getParam('id');
		$key = $this->_getParam('key');
		$flag = $this->_getParam('flag', null);
		$items = $this->_model->find($ids);
		foreach ($items as $item) {
			$item->{$key} = ($flag === null)?!$item->{$key}:$flag;
			$item->save();
		}
		$this->addMessage('Zmodyfikowanych rekordów: '.count($items));
		$this->_redirect($this->view->url(array('action'=>'index', 'id'=>null, 'key'=>null)));
	}
	
	public function deleteAction() {
		$ids = (array)$this->_getParam('id');
		$errors = 0;
		$ok = 0;
		
		foreach ($ids as $id) {
			try {
				$id = (int)$id;
				$this->_model->delete("id=$id");
				$ok ++;
			} catch (Exception $e) {
				$errors ++;
			}	
		}
		
		if ($errors > 0) {
			$this->addMessage('Wystąpił problem przy usuwaniu '.$errors.' rekordów', 'error');
		} 
		$this->addMessage('Usuniętych rekordów: '.$ok);
		$this->_redirect($this->view->url(array('action'=>'index', 'id'=>null)));
	}
	
	/**
	 * 
	 * obsługa checkboxów po lewej, przekierowujemy do metody z parametru
	 */
	public function checkAllAction() {
		$method = $this->_getParam('method');
		$this->_forward($method);
	}
	
	
	/**
	 * 
	 * wypełnia tabelę losowymi danymi
	 * @FIXME usunąć
	 */
	public function fillAction() {
		$meta = $this->_model->info();
		$meta = $meta['metadata'];
		
		$lorem  = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
		$loremL = strlen($lorem);
		
		for ($i=0;$i<=100;$i++) {
			$row = array();
			foreach ($meta as $k=>$info) {
				if ($k == 'id') continue;
				
				$v = null;
				
				if ($info['DATA_TYPE'] == 'int') {
					$v = rand(1,1000);
				}
				
				if ($info['DATA_TYPE'] == 'varchar') {
					$l = ceil($info['LENGTH'] / rand(4,8));
					$start = rand(0, $loremL-$l);
					$v = substr($lorem, $start, $l);
				}
				
				if ($info['DATA_TYPE'] == 'tinyint') {
					$v = rand(0,1);
				}
				
				if ($info['DATA_TYPE'] == 'timestamp') {
					$v = date('Y-m-d G:i:s', rand(time()-3600*24*365, time()));
				}
				
				$row[$k] = $v;
			}
			$this->_model->insert($row);
		}
		
		//_d($this->_model->info());
		exit;
	}
	
	protected function editForm() {
		$class = 'Form_'.ucfirst($this->_getParam('module')).'_'.ucfirst($this->_getParam('controller'));
		return new $class();
	}
	
	protected function createForm() {
		return $this->editForm();
	}
}